const jwt = require('jsonwebtoken');

/**
 * 生成访问令牌和刷新令牌
 */
function generateTokens(user) {
  const payload = {
    userId: user._id,
    username: user.username,
    email: user.email
  };

  const accessToken = jwt.sign(
    payload,
    process.env.JWT_SECRET || 'default-secret',
    { expiresIn: process.env.JWT_EXPIRES_IN || '1h' }
  );

  const refreshToken = jwt.sign(
    payload,
    process.env.JWT_REFRESH_SECRET || 'default-refresh-secret',
    { expiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '7d' }
  );

  return {
    accessToken,
    refreshToken,
    expiresIn: 3600 // 1小时，单位秒
  };
}

/**
 * 验证令牌
 */
function verifyToken(token, secret) {
  try {
    return jwt.verify(token, secret);
  } catch (error) {
    throw new Error(`令牌验证失败: ${error.message}`);
  }
}

/**
 * 解码令牌（不验证）
 */
function decodeToken(token) {
  return jwt.decode(token);
}

module.exports = {
  generateTokens,
  verifyToken,
  decodeToken
}; 